package com.sync.mutiParse;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel.MapMode;
import java.util.concurrent.atomic.AtomicBoolean;

import com.constants.Base;
import com.constants.Constants;

/**
 * 负责读块
 */
public final class ReadManager extends Base {
	public static final int count = 10;
	private static  ByteBuffer fileBuffers[] = new ByteBuffer[count];
	private static  ByteBuffer curFileBuffer = null;// 当前文件buffer
	private static volatile int num = 0;// 文件从1开始递增
	private static int blockID = 0; // 块号从0开始递增

	private static final AtomicBoolean lock = new AtomicBoolean(false);
	private static volatile boolean finished = false;

	public static void init() throws Exception {
		RandomAccessFile randomAccessFile = null;
		for (int i = 0; i < count; i++) {
			randomAccessFile = new RandomAccessFile(
					DATA_HOME + (1 + i) + FILE_SUFFIX, "r");
			fileBuffers[i] = randomAccessFile.getChannel()
					.map(MapMode.READ_ONLY, 0, randomAccessFile.length());
		}
		curFileBuffer = fileBuffers[0];
	}

	public static  Block readBlock(Block block) {
		byte[] blockBuffer = block.buffer;

		while (true) {
			if(lock.compareAndSet(false, true)){
				if (finished) {
					lock.set(false);
					return null;
				}
				// 设置块号ID
				block.id = blockID++;
				int remain = curFileBuffer.remaining();
				if (remain > Constants.BLOCK_SIZE_EXTEND) {
					int tmpLen = Constants.BLOCK_SIZE_NORMAL;
					curFileBuffer.get(blockBuffer, 0, tmpLen);
					while ((blockBuffer[tmpLen++] = curFileBuffer.get()) != 10) {}

					lock.set(false);
					block.limit = tmpLen;
				} else {
					block.limit = remain;
					curFileBuffer.get(blockBuffer, 0, remain);
					++num;
					loggerServer.info("读完第" + num + "个文件");
					if (num == count) {
						finished = true;
						lock.set(false);
						return null;
					}

					curFileBuffer = fileBuffers[num];
					lock.set(false);
				}
				break;
			}
		
		}
		return block;
	}

}
